<template>
  <Container class="mobile-form-modal">
    <div class="mobile-form-modal-inner">
      <div class="title">{{ $t("form.updateName.title") }}</div>
      <a-form class="form" :model="formData" ref="formRef">
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_1.label')"
          name="date"
          :rules="[
            {
              required: true,
              message: 'Date is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-date-picker v-model:value="formData.date">
            <template #suffixIcon> </template>
          </a-date-picker>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_2.label')"
          name="type"
          :rules="[
            {
              required: true,
              message: 'Model is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-select v-model:value="formData.type" @change="airModelChange">
            <a-select-option
              v-for="item in globalStore.airModelList"
              :key="item.title"
              :value="item.title"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          :label="$t('form.part_six.form.item_3.label')"
          name="family_id"
          :rules="[
            {
              validator: validateFamily,
              trigger: 'blur',
            },
          ]"
        >
          <a-select
            v-model:value="formData.family_title"
            :disabled="familyList.length == 0"
            @change="FamilySelectChange"
          >
            <a-select-option
              v-for="item in familyList"
              :key="item.title"
              :value="item.title"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_4.label')"
          name="ata"
          :rules="[
            {
              required: true,
              message: 'ATA is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-select v-model:value="formData.ata" @change="ataChange">
            <a-select-option
              v-for="item in globalStore.ataList"
              :key="item.no"
              :value="item.no"
              >{{ item.no }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_5.label')"
          name="engine_title"
          :rules="[
            {
              validator: validateEngine,
              trigger: 'blur',
            },
          ]"
        >
          <a-select
            :maxlength="30"
            v-model:value.trim="formData.engine_title"
            :disabled="engineList.length == 0"
          >
            <a-select-option
              v-for="item in engineList"
              :key="item.title"
              :value="item.title"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_6.label')"
          name="ac"
          :rules="[
            {
              required: true,
              message: 'AC is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-input :maxlength="50" v-model:value.trim="formData.ac"></a-input>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_7.label')"
          name="timespent"
          :rules="[
            {
              required: true,
              message: 'timespent is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-input
            :maxlength="30"
            v-model:value.trim="formData.timespent"
          ></a-input>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_8.label')"
          name="subject"
          :rules="[
            {
              validator: validateSubject,
              trigger: 'blur',
            },
          ]"
        >
          <div class="subject-inner">
            <a-textarea
              :maxlength="1000"
              v-if="formData.is_select == '2'"
              v-model:value.trim="formData.subject"
              :autoSize="{ minRows: 6, maxRows: 6 }"
            ></a-textarea>
            <a-select v-else v-model:value="formData.subject">
              <a-select-option
                v-for="item in subjectList"
                :key="item.id"
                :value="item.title"
                >{{ item.title }}</a-select-option
              >
            </a-select>
            <a-button
              class="custom-btn"
              type="primary"
              @click="toggleSubjectInput"
              >{{
                formData.is_select == "2"
                  ? $t("btnText.option")
                  : $t("btnText.custom")
              }}</a-button
            >
          </div>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_9.label')"
        >
          <div class="label-list">
            <div
              class="label-item"
              :class="item.checked ? 'active' : ''"
              @click="setLabelItem(item, 'action')"
              v-for="(item, index) in actionList"
              :key="index"
            >
              {{ item.label }}
            </div>
          </div>
        </a-form-item>
        <a-form-item
          class="form-item"
          :label="$t('form.part_six.form.item_10.label')"
        >
          <div class="label-list">
            <div
              class="label-item"
              :class="item.checked ? 'active' : ''"
              @click="setLabelItem(item, 'function')"
              v-for="(item, index) in functionList"
              :key="index"
            >
              {{ item.label }}
            </div>
          </div>
        </a-form-item>
      </a-form>
      <div class="footer-btn">
        <div class="footer-btn-inner">
          <a-button @click="goBack">{{ $t("btnText.cancel") }}</a-button>
          <a-button
            class="ensure-btn"
            :class="formIsValid ? '' : 'disabled'"
            type="primary"
            @click="continuePublish"
            >{{ $t("btnText.save") }}</a-button
          >
        </div>
      </div>
    </div>
  </Container>
</template>

<script setup lang="ts">
import {
  computed,
  getCurrentInstance,
  onBeforeUnmount,
  onMounted,
  ref,
} from "vue";
import { message } from "ant-design-vue";
import { useRouter } from "vue-router";
import { useGlobalStore, useMemberStore } from "../../store";
import type { PartSixData, SubjectItem } from "../../types/part";
import {
  postPartSixDataCreate,
  postPartSixDataUpdate,
  postPartSixEngineAll,
  postPartSixSelectFamily,
  postPartSixSubjectList,
} from "../../api/part";
import dayjs from "dayjs";
import type { EngineItem } from "../../types/global";

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;
const setAllChecked = (key: string) => {
  if (key == "action") {
    actionList.value.forEach((item) => {
      item.checked = false;
      formData.value[item.key] = "0";
    });
  }
  if (key == "function") {
    functionList.value.forEach((item) => {
      item.checked = false;
      formData.value[item.key] = "0";
    });
  }
};
const setLabelItem = (item, key: string) => {
  setAllChecked(key);
  if (item.checked) {
    item.checked = false;
    formData.value[item.key] = "0";
  } else {
    item.checked = true;
    formData.value[item.key] = "1";
  }
};
const router = useRouter();
const memberStore = useMemberStore();
const globalStore = useGlobalStore();
const paramsData = ref();
const initForm = () => {
  let data: string | PartSixData | null = sessionStorage.getItem("params");
  if (data) {
    data = JSON.parse(data) as PartSixData;
    paramsData.value = data;
    isAdd.value = false;
    formData.value.id = data.id;
    formData.value.date = formatDate(data.date);
    formData.value.type_id = data.type_id;
    formData.value.type = data.type!;
    formData.value.timespent = data.timespent;
    formData.value.subject = data.subject;
    formData.value.ac = data.ac;
    formData.value.ata_id = data.ata_id!;
    formData.value.ata = data.ata!;
    formData.value.subject = data.subject;
    formData.value.engine_title = data.engine_title!;
    formData.value.engine_id = data.engine_id!;
    formData.value.is_select = data.is_select!;
    formData.value.family_title = data.family_title!;
    formData.value.family_id = data.family_id!;
    initCheckedBox();
    getSubjectData();
    getSelectFamilyData();
  }
};
const toggleSubjectInput = () => {
  formData.value.is_select == "1"
    ? (formData.value.is_select = "2")
    : (formData.value.is_select = "1");
  getSubjectData();
};
const initCheckedBox = () => {
  Object.keys(paramsData.value).forEach((key) => {
    if (paramsData.value[key] == "1") {
      formData.value[key] = "1";
      actionList.value.forEach((item) => {
        if (item.key === key) {
          item.checked = true;
        }
      });
      functionList.value.forEach((item) => {
        if (item.key === key) {
          item.checked = true;
        }
      });
    }
  });
};
const isAdd = ref(true);
const formIsValid = computed(() => {
  let flag = true;
  if (!formData.value.date) flag = false;
  if (!formData.value.type) flag = false;
  if (!formData.value.ata) flag = false;
  if (!formData.value.engine_title) flag = false;
  if (!formData.value.ac) flag = false;
  if (!formData.value.timespent) flag = false;
  if (!formData.value.subject) flag = false;
  return flag;
});

const actionList = ref([
  {
    label: "SGH",
    key: "sgh",
  },
  {
    label: "R/I",
    key: "ri",
  },
  {
    label: "TS",
    key: "ts",
  },
  {
    label: "FOT",
    key: "fot",
  },
  {
    label: "ISP",
    key: "isp",
  },
  {
    label: "MP",
    key: "mp",
  },
]);

const functionList = ref([
  {
    label: "Execution Person",
    key: "execution_person",
  },
  {
    label: "Supervisor",
    key: "supervisor",
  },
  {
    label: "CRS",
    key: "crs",
  },
]);
// Form Rules
const validateFamily = (_rule: any, value: string) => {
  if (familyList.value.length == 0) {
    if (!formData.value.type_id)
      return Promise.reject("Please Select Model First!");
    return Promise.resolve();
  } else {
    if (!value && familyList.value.length > 0) {
      return Promise.reject("Family is required!");
    } else {
      return Promise.resolve();
    }
  }
};

const validateEngine = (_rule: any, value: string) => {
  if (engineList.value.length == 0) {
    if (!formData.value.family_id)
      return Promise.reject("Please Select Family First!");
    return Promise.resolve();
  } else {
    if (!value && familyList.value.length > 0) {
      return Promise.reject("Engine is required!");
    } else {
      return Promise.resolve();
    }
  }
};
const validateSubject = (_rule: any, value: string) => {
  if (engineList.value.length == 0) {
    if (!formData.value.family_id && !formData.value.ata)
      return Promise.reject("Please Select Family And ATA First!");
    return Promise.resolve();
  } else {
    if (!value && familyList.value.length > 0) {
      return Promise.reject("Subject is required!");
    } else {
      return Promise.resolve();
    }
  }
};

// 发布
const formData = ref({
  date: "",
  type: "",
  type_id: "",
  ac: "",
  ata: "",
  ata_id: "",
  subject: "",
  timespent: "",
  sgh: "0",
  ri: "0",
  ts: "0",
  fot: "0",
  isp: "0",
  mp: "0",
  engine_title: "",
  engine_id: "",
  execution_person: "0",
  supervisor: "0",
  crs: "0",
  family_id: "",
  family_title: "",
  is_select: "1",
});

const formRef = ref();
const getEngineId = (title: string) => {
  let id = "";
  globalStore.engineList!.forEach((item) => {
    if (item.title == title) {
      id = item.id + "";
    }
  });
  return id;
};
const engineList = ref<any[]>([]);
const FamilySelectChange = async (title) => {
  let sel_item = familyList.value.find((item) => item.title == title);
  formData.value.family_id = sel_item.id;
  let engine_ids = sel_item.engine_ids;
  let res = await postPartSixEngineAll(engine_ids);
  engineList.value = res.data;
};
const familyList = ref<any[]>([]);
const getSelectFamilyData = async () => {
  let type_id = formData.value.type_id;
  if (type_id) {
    let res = await postPartSixSelectFamily(type_id);
    if (res.code == 200) {
      familyList.value = res.data || [];
      if (paramsData.value) {
        FamilySelectChange(formData.value.family_title);
      }
    }
  }
};
const ataChange = () => {
  formData.value.ata_id = globalStore.getAtaIdByAtaTitle(formData.value.ata!);
  getSubjectData();
};

const airModelChange = () => {
  formData.value.engine_title = "";
  formData.value.type_id = globalStore.getTypeIdByTypeTitle(
    formData.value.type!
  );
  familyList.value = [];
  engineList.value = [];
  formData.value.engine_id = "";
  formData.value.family_title = "";
  getSubjectData();
  getSelectFamilyData();
};
const subjectList = ref<SubjectItem[]>([]);
const getSubjectData = async () => {
  if (formData.value.is_select != "1") return;
  let family_id = formData.value.family_id;
  let ata_id = formData.value.ata_id;
  if (family_id && ata_id) {
    let res = await postPartSixSubjectList(family_id, ata_id);
    if (res.code == 200) {
      subjectList.value = res.data;
    }
  }
};

const submiting = ref(false);
const continuePublish = () => {
  if (!formIsValid.value) return;
  formRef.value.validate().then(async () => {
    formData.value.engine_id = getEngineId(formData.value.engine_title!);
    formData.value.ata_id = globalStore.getAtaIdByAtaTitle(formData.value.ata!);
    formData.value.type_id = globalStore.getTypeIdByTypeTitle(
      formData.value.type!
    );
    let obj = {
      date: dayjs(formData.value.date).format("YYYY-MM-DD"),
    };
    let params = JSON.parse(JSON.stringify(formData.value));
    Object.assign(params, obj);
    submiting.value = true;
    if (isAdd.value) {
      let res = await postPartSixDataCreate(params);
      if (res.code == 200) {
        goBack();
        message.success($t("message.success.add"));
      } else {
        message.error($t("message.error.add"));
      }
    } else {
      let res = await postPartSixDataUpdate(params);
      if (res.code == 200) {
        goBack();
        message.success($t("message.success.update"));
      } else {
        goBack();
        message.error($t("message.error.update"));
      }
    }
    submiting.value = false;
  });
};
const goBack = () => {
  router.go(-1);
};

onBeforeUnmount(() => {
  sessionStorage.removeItem("params");
  sessionStorage.removeItem("m_lang");
});

onMounted(() => {
  initForm();
});
</script>
<style lang="less">
.mobile-form-modal {
  .wrap-container > .wrap-pl {
    padding-bottom: 0 !important;
  }
}
</style>
<style scoped lang="less">
@import url("./common.less");
:deep(.form) {
  .ant-form-item {
    .ant-row {
      justify-content: space-between;
      width: 100%;
      .ant-col {
        padding-bottom: 0;
        flex: 0 0 auto !important;
        .ant-input {
          padding: 0 !important;
        }
        .ant-select {
          min-width: 600px;
          text-align: right;
          .ant-select-selector {
            border: 1px solid transparent !important;
            box-shadow: 0 0 0 transparent !important;
            input {
              text-align: right;
            }
          }
        }
      }
    }
  }
  .custom-btn {
    height: auto !important;
    padding: 8px 30px !important;
    border-radius: 20px !important;
    margin: 10px 0 10px auto;
  }
}

.label-list {
  display: flex;
  flex-wrap: wrap;
  font-size: 72px;
  align-items: center;
  gap: 42px;
  .label-item {
    padding: 20px 40px;
    cursor: pointer;
    border-radius: 8px;
    border: 1px solid #ccc;
    &.active {
      background-color: #05204b;
      border-color: transparent;
      color: #fff;
    }
  }
}
</style>
